<template>
  <div style="height: 100%" v-loading="loading">
    <van-nav-bar title="移库信息" left-text="返回" left-arrow @click-left="goBack" :right-text="postingDate" @click-right="setPostDate"/>
    <van-calendar v-model="showCalendar" @confirm="onConfirm" :min-date="minDate" :max-date="maxDate"/>
    <van-cell-group :v-model="tableData" style="
        overflow: scroll;
        height: 520px;
        ::-webkit-scrollbar {
          display: none;
        }
      ">
       <van-row >
        <van-col span="14">
          <van-field v-model="tableData.materialno" label="物料编码" readonly />
          </van-col>
          <van-col span="10">
            <van-field v-model="tableData.specification" label="规格" readonly label-width="30%"/>
          </van-col>
          </van-row>
      <van-field v-model="tableData.materialdes" label="物料描述" readonly />
      <van-field v-model="tableData.batchno" label="批号" readonly />
      <van-field v-model="tableData.packinglotno" label="包装批" readonly />
      <van-field v-model="tableData.productionlotno" label="生产批" readonly />
      <van-row style="border: solid 1px #3793fb; border-radius: 5px">
        <van-col span="24">
          <el-autocomplete id="autocomplete" v-model="tableData.locationfrom" value-key="codeanddes" label="转出库位" :rules="{
    required: true,
    message: '请选择库位',
    trigger: 'blur',
  }" :fetch-suggestions="storageLocationFromSearch" placeholder="转出库位" style="width: 100%;"></el-autocomplete>
        </van-col>
      </van-row>          
      <van-row style="border: solid 1px #3793fb; border-radius: 5px">
        <van-col span="12">
          <van-field v-model="tableData.noofbarrels" label="桶数" @input="noOfBarrelsChange" v-if="dc_flag !== 'X'"/>
        </van-col>
        <van-col span="12"><van-field v-model="tableData.totalquantity" label="总数量" style="border-radius: 5px" />
        </van-col>
      </van-row>
      <van-row style="border: solid 1px #3793fb; border-radius: 5px">
        <van-col span="24">
          <el-autocomplete id="autocomplete" v-model="tableData.locationto" value-key="codeanddes" label="库位" :rules="{
    required: true,
    message: '请选择库位',
    trigger: 'blur',
  }" :fetch-suggestions="storageLocationSearch" placeholder="转入库位" style="width: 100%;"></el-autocomplete>
        </van-col>
      </van-row>
      <van-field style="border: solid 1px #3793fb; border-radius: 5px" v-model="code_input" ref="code_input"
        placeholder="请扫描吨槽码" left-icon="scan" @input="onScanBarrelCode" v-if="dc_flag == 'X'"/>
      <van-swipe @change="onChange" width="100%" ref="swiper" style="border: solid #3793fb 1px;border-top:none">
        <van-swipe-item v-for="(domain, domainIndex) in tableData.details" :key="domainIndex" >
          <van-field v-model="domain.numberOfBarrels" label="吨槽号" readonly></van-field>
          <van-field v-model="domain.quantity" label="数量"  @input="quantityChange" ></van-field>
          <van-button @click="onDeleteBarrel(domainIndex)" class="custom-swipe-delete" v-if="current >= 0"
            color="linear-gradient(to right, #ff6034, #ee0a24)">
            删除
          </van-button>
        </van-swipe-item>
        <template #indicator>
          <div class="custom-indicator" v-if="current >= 0">{{ current + 1 }}/{{ totalSize }}</div>
        </template>
      </van-swipe>
    </van-cell-group>
    <van-button @click="onSubmit" style="
        position: fixed;
        bottom: 0px;
        border: #3793fb solid 1px;
        border-radius: 2px;
        background-color: #3793fb;
        line-height: var(--footer-height);
      " type="primary" block>移库过账</van-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: {
        details: []
      },
      storageLocationList: [],
      storageLocationListFrom:[],
      loading: false,
      index: 0,
      totalSize: 0,
      current: -1,
      code_input: '',
      dc_flag:false,
      showCalendar: false,
      postingDate: this.getNowFormatDate(new Date()),
      minDate:this.getMonthBeforeDate(),
      maxDate:this.getMonthAfterDate()
    };
  },
  mounted() {
    //原料入库信息
    this.getMoveLocationDetails(this.$route.query.codeInfo);
    //获取库位List
    this.getStorageLocationList();
  },
  methods: {  
    setPostDate() {
      this.showCalendar = true;
    },
    onConfirm(date) {
      this.showCalendar = false;
      this.$dialog.confirm({
        title: '过账日期',
        message: '此选择将更改ERP过账日期',
      })
        .then(() => {
          this.postingDate = this.getNowFormatDate(date);
        })
        .catch(() => {
        });
    },
    async getMoveLocationDetails(codeInfoStr) {
      let scanInfo = {
        code: codeInfoStr + "," + localStorage.getItem("plant"),
      };
      const { data: res } = await this.$http.post(
        "/MoveLocationInfo",
        scanInfo
      );
      this.tableData = res[0];
      this.storageLocationListFrom = res[0].stocks;
      this.dc_flag = res[0].zifdc;
    },
    async getStorageLocationList() {
      let scanInfo = {
        plant: localStorage.getItem("plant"),
      };
      const { data: res } = await this.$http.post(
        "/StorageLocationList",
        scanInfo
      );
      this.storageLocationList = res;
    },
    //返回
    goBack() {
      this.backToHome();
    },

    onScanBarrelCode(event) {
      this.getBucket(event);
    },
    async getBucket(bucketNo) {
      let scanInfo = {
        code: bucketNo,
        materialno: this.tableData.materialno,
        batchno: this.tableData.batchno,
        plant: localStorage.getItem("plant"),
        location: this.tableData.locationfrom,
      };
      const { data: res } = await this.$http.post(
          "/ProductionVerifyBucket",
          scanInfo
      );
      console.log("res",res);
      if (res.length && res[0].bucketnumber && 'E' !== res[0].type) {
        var requestData = this.tableData;
        for (var i in requestData.details) {
          if(requestData.details[i].numberOfBarrels === res[0].bucketnumber){
            this.$message({
              message: "扫描失败，请勿重复扫描同一桶号",
              type: "error",
            });
            this.code_input = '';
            return
          }
        }
        if('占用' !== res[0].bucketstatus){
          this.$toast.fail('条码信息错误,非占用状态');
          this.code_input = '';
          return
        }
        var specification = this.tableData.specification;
        this.tableData.details.push({ numberOfBarrels: res[0].bucketnumber, quantity: specification });
        this.tableData.noofbarrels = parseInt(this.tableData.noofbarrels) + 1;
        this.tableData.totalquantity = parseInt(this.tableData.totalquantity) + parseInt(specification);
        this.totalSize = this.tableData.details.length;
        this.current = this.totalSize - 1;
        this.$refs.swiper.swipeTo(this.current);
        this.code_input = '';
      } else {
        this.code_input = '';
        if(res.length){
          this.$toast.fail(res[0].message);
        }else{
          this.$toast.fail('条码信息错误');
        }
      }
    },
    onChange(index) {
      this.current = index;
    },
    //库位搜索帮助
    storageLocationSearch(queryString, cb) {
      var storageLocationList = this.storageLocationList;
      var results = queryString
        ? storageLocationList.filter(this.createFilter(queryString))
        : storageLocationList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    //转出库位搜索帮助
    storageLocationFromSearch(queryString, cb) {
      var storageLocationList = this.storageLocationListFrom;
      var results = queryString
        ? storageLocationList.filter(this.createFilter(queryString))
        : storageLocationList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },    
    createFilter(queryString) {
      return (storageLocation) => {
        return (          
          storageLocation.codeanddes
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    onDeleteBarrel(domainIndex) {
      this.tableData.totalquantity -= this.tableData.details[domainIndex].quantity;
      this.tableData.details.splice(domainIndex, 1);
      this.tableData.noofbarrels -= 1;
      this.totalSize = this.tableData.details.length;
      if (this.current > this.totalSize - 1) {
        this.current = this.totalSize - 1;
      }
      this.$refs.swiper.swipeTo(this.current);
    },
    quantityChange(){
      var total = 0;
      for( var i in this.tableData.details){
        if(this.tableData.details[i].quantity !== ''){
        total +=  parseInt(this.tableData.details[i].quantity);
        }
        this.tableData.totalquantity = total;
      }
    },
    noOfBarrelsChange(){
      if( this.tableData.details && this.tableData.specification !== ''){
        this.tableData.totalquantity =  this.tableData.specification * this.tableData.noofbarrels;
      }
    },
    //移过账
    onSubmit() {
      this.loading = true;
      setTimeout(() =>{
        this.loading = false;
        this.postMoveLocation();
      }, 1000);
    },
    async postMoveLocation(){
      var requestData = this.tableData;
      var details = [];
      for (var i in requestData.details) {
        details.push({
          numberOfBarrels: requestData.details[i].numberOfBarrels,
          quantity:
            requestData.details[i].quantity,
        });
      }      
      let inputInfo = {
        materialNo: requestData.materialno,
        plant: localStorage.getItem("plant"),
        batchNo: requestData.batchno,
        batchNoTo:requestData.batchno,
        totalQuantity:requestData.totalquantity,
        locationFrom:requestData.locationfrom.split("|")[0]+"|"+requestData.locationfrom.split("|")[1],
        locationTo:requestData.locationto,
        postdate:this.postingDate,      
        persnumber:localStorage.getItem("erpId"),
        details: details,
        zifdc:this.dc_flag,
      };
      const { data: res } = await this.$http.post(
        "/postMoveLocation",
        inputInfo
      );
      var response = res[0];
      if (response.type == "S") {
        this.$toast.success(response.message);
        setTimeout(() => {
          this.$router.push("/HomePage");
        }, 1000);
      } else if (response.type == "E") {
        this.$message({
          message: response.message,
          type: "error",
        });
      } else {
        this.$message({
          message: "移库失败，请联系系统维护人员",
          type: "error",
        });
      }      
    }
  },
};
</script>

<style>
.autocompleteLabel {
  -webkit-box-flex: 0;
  -webkit-flex: none;
  flex: none;
  box-sizing: border-box;
  width: 6.2em;
  margin-right: 12px;
  color: #646566;
  text-align: left;
  word-wrap: break-word;
}

.custom-indicator {
  position: absolute;
  right: 5px;
  bottom: 5px;
  padding: 2px 5px;
  font-size: 12px;
  background: rgba(0, 0, 0, 0.1);
}

.custom-swipe-delete {
  font-size: 12px;
  height: 40%;
  margin-left: 5%;
}
</style>
